<template>
  <div class="lectures">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">课程讲义</h1>
        <p class="page-subtitle">系统学习前端开发理论知识</p>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="content-section">
      <div class="container">
        <el-row :gutter="20">
          <!-- 左侧导航 -->
          <el-col :xs="24" :sm="6" :md="5">
            <div class="sidebar">
              <div class="sidebar-header">
                <h3>课程讲义</h3>
                <el-tag type="info" size="small">共24讲</el-tag>
              </div>
              
              <!-- 搜索框 -->
              <div class="search-box">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索讲义内容"
                  prefix-icon="Search"
                  size="small"
                  @input="handleSearch"
                />
              </div>
              
              <el-menu
                :default-active="activeLecture.toString()"
                class="lecture-menu"
                @select="handleLectureSelect"
              >
                <template v-for="lecture in filteredLectures" :key="lecture.id">
                  <el-menu-item :index="lecture.id.toString()">
                    <div class="menu-item-content">
                      <div class="lecture-info">
                        <span class="lecture-title">第{{ lecture.id }}讲</span>
                        <span class="lecture-subtitle">{{ lecture.title }}</span>
                      </div>
                      <div class="lecture-meta">
                        <el-icon v-if="lecture.completed" color="#67c23a" size="16">
                          <CircleCheck />
                        </el-icon>
                        <span class="duration">{{ lecture.duration }}</span>
                      </div>
                    </div>
                  </el-menu-item>
                </template>
              </el-menu>
            </div>
          </el-col>

          <!-- 右侧内容 -->
          <el-col :xs="24" :sm="18" :md="19">
            <div class="content-card">
              <div class="content-header">
                <div class="lecture-info">
                  <div class="lecture-number">第{{ currentLecture?.id }}讲</div>
                  <h2>{{ currentLecture?.title }}</h2>
                  <p>{{ currentLecture?.description }}</p>
                </div>
                <div class="lecture-actions">
                  <el-button-group>
                    <el-button 
                      :disabled="activeLecture <= 1"
                      @click="previousLecture"
                      icon="ArrowLeft"
                    >
                      上一讲
                    </el-button>
                    <el-button 
                      :disabled="activeLecture >= lectures.length"
                      @click="nextLecture"
                      icon="ArrowRight"
                    >
                      下一讲
                    </el-button>
                  </el-button-group>
                  <el-button 
                    type="primary" 
                    @click="markAsCompleted"
                    :disabled="currentLecture?.completed"
                  >
                    {{ currentLecture?.completed ? '已完成' : '标记完成' }}
                  </el-button>
                </div>
              </div>

              <!-- 讲义内容 -->
              <div class="lecture-content">
                <el-tabs v-model="activeTab" class="lecture-tabs">
                  <el-tab-pane label="讲义内容" name="content">
                    <div class="markdown-content" v-html="renderMarkdown(currentLecture?.content || '')"></div>
                  </el-tab-pane>
                  
                  <el-tab-pane label="课件下载" name="slides">
                    <div class="slides-section">
                      <div class="slides-list">
                        <div 
                          v-for="slide in currentLecture?.slides"
                          :key="slide.id"
                          class="slide-item"
                        >
                          <div class="slide-info">
                            <el-icon size="24" color="#409eff">
                              <Document />
                            </el-icon>
                            <div class="slide-details">
                              <h4>{{ slide.title }}</h4>
                              <p>{{ slide.description }}</p>
                              <span class="file-size">{{ slide.size }}</span>
                            </div>
                          </div>
                          <el-button 
                            type="primary" 
                            size="small"
                            @click="downloadSlide(slide)"
                          >
                            下载
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>
                  
                  <el-tab-pane label="相关资源" name="resources">
                    <div class="resources-section">
                      <div class="resource-category" v-for="category in currentLecture?.resources" :key="category.type">
                        <h4>{{ category.title }}</h4>
                        <div class="resource-list">
                          <div 
                            v-for="resource in category.items"
                            :key="resource.id"
                            class="resource-item"
                          >
                            <el-icon size="20">
                              <component :is="getResourceIcon(resource.type)" />
                            </el-icon>
                            <div class="resource-info">
                              <a :href="resource.url" target="_blank" class="resource-link">
                                {{ resource.title }}
                              </a>
                              <p>{{ resource.description }}</p>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>
                  
                  <el-tab-pane label="笔记" name="notes">
                    <div class="notes-section">
                      <div class="notes-editor">
                        <el-input
                          v-model="userNotes"
                          type="textarea"
                          :rows="15"
                          placeholder="在这里记录你的学习笔记..."
                          @blur="saveNotes"
                        />
                      </div>
                      <div class="notes-actions">
                        <el-button @click="saveNotes">保存笔记</el-button>
                        <el-button @click="exportNotes">导出笔记</el-button>
                      </div>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 学习进度统计 -->
    <div class="progress-section">
      <div class="container">
        <div class="progress-card">
          <div class="progress-header">
            <h3>学习进度</h3>
            <el-tag type="success">{{ completedCount }}/{{ lectures.length }} 已完成</el-tag>
          </div>
          <div class="progress-content">
            <el-progress 
              :percentage="progressPercentage" 
              :stroke-width="8"
              :show-text="false"
            />
            <div class="progress-stats">
              <div class="stat-item">
                <span class="stat-label">完成率</span>
                <span class="stat-value">{{ progressPercentage }}%</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">学习时长</span>
                <span class="stat-value">{{ totalStudyTime }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  CircleCheck, 
  ArrowLeft, 
  ArrowRight, 
  Document, 
  Link, 
  VideoPlay,
  Search
} from '@element-plus/icons-vue'

// 响应式数据
const activeLecture = ref(1)
const activeTab = ref('content')
const searchKeyword = ref('')
const userNotes = ref('')

// 讲义数据
const lectures = ref([
  {
    id: 1,
    title: 'Web前端开发概述',
    description: '了解前端开发的历史、现状和发展趋势，掌握前端开发的基本概念和技术栈。',
    duration: '45分钟',
    completed: false,
    content: `# Web前端开发概述

## 学习目标
- 理解前端开发的概念和作用
- 了解前端技术的发展历程
- 掌握现代前端开发技术栈
- 认识前端开发的职业发展路径

## 什么是前端开发

前端开发是指运用HTML、CSS、JavaScript等技术，开发用户可以浏览和交互的网页界面的过程。前端开发者需要关注用户体验、界面设计、交互逻辑等方面。

### 前端开发的核心技术

1. **HTML (HyperText Markup Language)**
   - 网页的结构和内容
   - 语义化标签的使用
   - HTML5新特性

2. **CSS (Cascading Style Sheets)**
   - 网页的样式和布局
   - 响应式设计
   - CSS3动画和特效

3. **JavaScript**
   - 网页的交互和逻辑
   - DOM操作
   - 异步编程

## 前端技术发展历程

### 静态网页时代 (1990s-2000s)
- 纯HTML页面
- 简单的CSS样式
- 基本的JavaScript交互

### 动态网页时代 (2000s-2010s)
- AJAX技术的兴起
- jQuery等库的流行
- 前后端分离的概念

### 现代前端时代 (2010s-至今)
- 前端框架的兴起 (React, Vue, Angular)
- 构建工具的发展 (Webpack, Vite)
- 移动端开发的重要性

## 现代前端技术栈

### 基础技术
- HTML5
- CSS3
- ES6+ JavaScript

### 前端框架
- **React**: Facebook开发的组件化框架
- **Vue.js**: 渐进式JavaScript框架
- **Angular**: Google开发的完整解决方案

### 构建工具
- **Webpack**: 模块打包工具
- **Vite**: 新一代构建工具
- **Parcel**: 零配置构建工具

### 包管理器
- **npm**: Node.js包管理器
- **yarn**: Facebook开发的包管理器
- **pnpm**: 高效的包管理器

## 前端开发的职业发展

### 技能要求
1. **技术技能**
   - 熟练掌握HTML、CSS、JavaScript
   - 至少精通一种前端框架
   - 了解构建工具和开发流程
   - 掌握版本控制工具(Git)

2. **软技能**
   - 良好的沟通能力
   - 团队协作精神
   - 持续学习的能力
   - 问题解决能力

### 职业路径
- **初级前端开发工程师**
- **中级前端开发工程师**
- **高级前端开发工程师**
- **前端架构师**
- **全栈开发工程师**

## 学习建议

1. **循序渐进**: 从基础的HTML、CSS开始，逐步学习JavaScript和框架
2. **实践为主**: 多做项目，在实践中学习和提高
3. **关注趋势**: 关注前端技术的发展趋势，及时学习新技术
4. **社区参与**: 参与开源项目，与其他开发者交流学习

## 本课程安排

本课程将通过24讲的内容，系统地介绍前端开发的各个方面：

- **第1-6讲**: HTML和CSS基础
- **第7-12讲**: JavaScript基础和进阶
- **第13-18讲**: Vue.js框架学习
- **第19-24讲**: 项目实战和高级主题

每一讲都包含理论讲解、实例演示和实践练习，帮助大家全面掌握前端开发技能。`,
    slides: [
      {
        id: 1,
        title: '前端开发概述.pptx',
        description: '课程介绍和前端技术概览',
        size: '2.5MB'
      }
    ],
    resources: [
      {
        type: 'links',
        title: '相关链接',
        items: [
          {
            id: 1,
            title: 'MDN Web Docs',
            description: '权威的Web技术文档',
            url: 'https://developer.mozilla.org/',
            type: 'link'
          },
          {
            id: 2,
            title: 'Can I Use',
            description: '浏览器兼容性查询',
            url: 'https://caniuse.com/',
            type: 'link'
          }
        ]
      },
      {
        type: 'videos',
        title: '推荐视频',
        items: [
          {
            id: 3,
            title: '前端发展史',
            description: '了解前端技术的发展历程',
            url: '#',
            type: 'video'
          }
        ]
      }
    ]
  },
  {
    id: 2,
    title: 'HTML基础语法',
    description: '学习HTML的基本语法、常用标签和文档结构。',
    duration: '50分钟',
    completed: true,
    content: `# HTML基础语法

## 学习目标
- 掌握HTML的基本语法规则
- 了解HTML文档的基本结构
- 学会使用常用的HTML标签
- 理解HTML标签的属性和用法

## HTML简介

HTML (HyperText Markup Language) 是用于创建网页的标准标记语言。它使用标签来描述网页的结构和内容。

### HTML文档结构

一个标准的HTML文档包含以下基本结构：

\`\`\`html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>页面标题</title>
</head>
<body>
    <!-- 页面内容 -->
</body>
</html>
\`\`\`

### 基本语法规则

1. **标签**: HTML使用尖括号包围的关键词来定义标签
2. **开始标签和结束标签**: 大多数标签都有开始标签和结束标签
3. **自闭合标签**: 某些标签是自闭合的，如 \`<img>\`、\`<br>\`
4. **属性**: 标签可以包含属性来提供额外信息
5. **嵌套**: 标签可以嵌套使用，但必须正确嵌套

## 常用HTML标签

### 文本标签

- \`<h1>\` 到 \`<h6>\`: 标题标签
- \`<p>\`: 段落标签
- \`<span>\`: 行内文本标签
- \`<strong>\`: 重要文本（粗体）
- \`<em>\`: 强调文本（斜体）

### 链接和图片

- \`<a>\`: 链接标签
- \`<img>\`: 图片标签

### 列表标签

- \`<ul>\`: 无序列表
- \`<ol>\`: 有序列表
- \`<li>\`: 列表项

### 表格标签

- \`<table>\`: 表格
- \`<tr>\`: 表格行
- \`<td>\`: 表格单元格
- \`<th>\`: 表格标题单元格

## 实践练习

创建一个简单的个人介绍页面，包含：
1. 页面标题
2. 个人信息
3. 技能列表
4. 联系方式`,
    slides: [
      {
        id: 2,
        title: 'HTML基础语法.pptx',
        description: 'HTML语法规则和常用标签',
        size: '3.1MB'
      }
    ],
    resources: [
      {
        type: 'links',
        title: '参考资料',
        items: [
          {
            id: 4,
            title: 'HTML标签参考',
            description: 'W3Schools HTML标签参考',
            url: 'https://www.w3schools.com/tags/',
            type: 'link'
          }
        ]
      }
    ]
  }
  // 可以继续添加更多讲义...
])

// 计算属性
const currentLecture = computed(() => {
  return lectures.value.find(lecture => lecture.id === activeLecture.value)
})

const filteredLectures = computed(() => {
  if (!searchKeyword.value) {
    return lectures.value
  }
  return lectures.value.filter(lecture => 
    lecture.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    lecture.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

const completedCount = computed(() => {
  return lectures.value.filter(lecture => lecture.completed).length
})

const progressPercentage = computed(() => {
  return Math.round((completedCount.value / lectures.value.length) * 100)
})

const totalStudyTime = computed(() => {
  const totalMinutes = lectures.value
    .filter(lecture => lecture.completed)
    .reduce((total, lecture) => {
      const minutes = parseInt(lecture.duration.replace('分钟', ''))
      return total + minutes
    }, 0)
  
  const hours = Math.floor(totalMinutes / 60)
  const minutes = totalMinutes % 60
  return hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`
})

// 方法
const handleLectureSelect = (key) => {
  activeLecture.value = parseInt(key)
  activeTab.value = 'content'
  loadUserNotes()
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中实现
}

const previousLecture = () => {
  if (activeLecture.value > 1) {
    activeLecture.value--
    loadUserNotes()
  }
}

const nextLecture = () => {
  if (activeLecture.value < lectures.value.length) {
    activeLecture.value++
    loadUserNotes()
  }
}

const markAsCompleted = () => {
  if (currentLecture.value) {
    currentLecture.value.completed = true
    ElMessage.success('已标记为完成')
    saveProgress()
  }
}

const renderMarkdown = (content) => {
  // 简单的Markdown渲染
  return content
    .replace(/^# (.*$)/gim, '<h1>$1</h1>')
    .replace(/^## (.*$)/gim, '<h2>$1</h2>')
    .replace(/^### (.*$)/gim, '<h3>$1</h3>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`([^`]+)`/g, '<code>$1</code>')
    .replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
    .replace(/\n/g, '<br>')
}

const downloadSlide = (slide) => {
  ElMessage.info(`开始下载: ${slide.title}`)
  // 实际下载逻辑
}

const getResourceIcon = (type) => {
  const icons = {
    'link': 'Link',
    'video': 'VideoPlay',
    'document': 'Document'
  }
  return icons[type] || 'Document'
}

const saveNotes = () => {
  // 保存笔记到本地存储
  const notesKey = `lecture_notes_${activeLecture.value}`
  localStorage.setItem(notesKey, userNotes.value)
  ElMessage.success('笔记保存成功')
}

const loadUserNotes = () => {
  // 从本地存储加载笔记
  const notesKey = `lecture_notes_${activeLecture.value}`
  userNotes.value = localStorage.getItem(notesKey) || ''
}

const exportNotes = () => {
  if (!userNotes.value.trim()) {
    ElMessage.warning('没有笔记内容可导出')
    return
  }
  
  const blob = new Blob([userNotes.value], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `第${activeLecture.value}讲_笔记.txt`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('笔记导出成功')
}

const saveProgress = () => {
  // 保存学习进度
  const progress = {
    completedLectures: lectures.value.filter(l => l.completed).map(l => l.id),
    lastAccessed: new Date().toISOString()
  }
  localStorage.setItem('lecture_progress', JSON.stringify(progress))
}

const loadProgress = () => {
  // 加载学习进度
  const saved = localStorage.getItem('lecture_progress')
  if (saved) {
    const progress = JSON.parse(saved)
    progress.completedLectures.forEach(id => {
      const lecture = lectures.value.find(l => l.id === id)
      if (lecture) {
        lecture.completed = true
      }
    })
  }
}

// 监听讲义变化，自动保存进度
watch(() => lectures.value.map(l => l.completed), () => {
  saveProgress()
}, { deep: true })

onMounted(() => {
  loadProgress()
  loadUserNotes()
})
</script>

<style scoped>
.content-section {
  padding: 40px 0;
  min-height: calc(100vh - 200px);
}

.sidebar {
  position: sticky;
  top: 20px;
  height: calc(100vh - 140px); /* 减去页面头部高度和一些边距 */
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px 8px 0 0;
  border-bottom: 1px solid #eee;
}

.sidebar-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.2rem;
}

.search-box {
  padding: 15px 20px;
  background: white;
  border-bottom: 1px solid #eee;
}

.lecture-menu {
  border: none;
  border-radius: 0 0 8px 8px;
  flex: 1;
  overflow-y: auto;
}

.menu-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.lecture-info {
  flex: 1;
}

.lecture-title {
  display: block;
  font-weight: 600;
  margin-bottom: 4px;
  color: #409eff;
}

.lecture-subtitle {
  display: block;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.lecture-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.duration {
  font-size: 11px;
  color: #c0c4cc;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 30px;
  border-bottom: 1px solid #eee;
}

.content-header .lecture-info {
  flex: 1;
}

.lecture-number {
  display: inline-block;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  margin-bottom: 10px;
}

.content-header h2 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 1.8rem;
}

.content-header p {
  margin: 0;
  color: #7f8c8d;
  line-height: 1.6;
}

.lecture-actions {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.lecture-content {
  padding: 0;
}

.lecture-tabs {
  padding: 20px 30px;
}

.markdown-content {
  line-height: 1.8;
  color: #2c3e50;
  max-width: none;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3 {
  color: #2c3e50;
  margin: 25px 0 15px 0;
}

.markdown-content h1 {
  font-size: 2rem;
  border-bottom: 2px solid #eee;
  padding-bottom: 10px;
}

.markdown-content h2 {
  font-size: 1.5rem;
  color: #409eff;
}

.markdown-content h3 {
  font-size: 1.2rem;
}

.markdown-content code {
  background: #f1f2f6;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  color: #e74c3c;
}

.markdown-content pre {
  background: #2c3e50;
  color: #ecf0f1;
  padding: 20px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 20px 0;
}

.markdown-content pre code {
  background: none;
  color: inherit;
  padding: 0;
}

.slides-section,
.resources-section,
.notes-section {
  padding: 20px 0;
}

.slides-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.slide-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.slide-item:hover {
  background: #e3f2fd;
  transform: translateY(-2px);
}

.slide-info {
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
}

.slide-details h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
}

.slide-details p {
  margin: 0 0 5px 0;
  color: #7f8c8d;
  font-size: 0.9rem;
}

.file-size {
  font-size: 0.8rem;
  color: #95a5a6;
}

.resource-category {
  margin-bottom: 30px;
}

.resource-category h4 {
  color: #2c3e50;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.resource-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.resource-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.resource-item:hover {
  background: #e8f4fd;
}

.resource-info {
  flex: 1;
}

.resource-link {
  color: #409eff;
  text-decoration: none;
  font-weight: 500;
}

.resource-link:hover {
  text-decoration: underline;
}

.resource-info p {
  margin: 5px 0 0 0;
  color: #7f8c8d;
  font-size: 0.9rem;
}

.notes-editor {
  margin-bottom: 20px;
}

.notes-editor :deep(.el-textarea__inner) {
  font-family: 'Courier New', monospace;
  line-height: 1.6;
}

.notes-actions {
  display: flex;
  gap: 10px;
}

.progress-section {
  padding: 40px 0;
  background: #f8f9fa;
}

.progress-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.progress-header h3 {
  margin: 0;
  color: #2c3e50;
}

.progress-content {
  margin-bottom: 20px;
}

.progress-stats {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  color: #7f8c8d;
  font-size: 0.9rem;
  margin-bottom: 5px;
}

.stat-value {
  display: block;
  color: #2c3e50;
  font-size: 1.2rem;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-header {
    flex-direction: column;
    gap: 20px;
    align-items: flex-start;
  }
  
  .lecture-actions {
    width: 100%;
    flex-direction: column;
  }
  
  .lecture-actions .el-button-group {
    width: 100%;
  }
  
  .lecture-actions .el-button-group .el-button {
    flex: 1;
  }
  
  .slide-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .progress-stats {
    flex-direction: column;
    gap: 15px;
  }
  
  .sidebar {
    position: static;
    margin-bottom: 20px;
  }
  
  .lecture-tabs {
    padding: 15px 20px;
  }
}
</style>